package com.gin.kotlin.gf2gamecommunity.routes

import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Face
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import com.gin.kotlin.form.CommentReplyForm
import com.gin.kotlin.gf2gamecommunity.R
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.composable.Loading
import com.gin.kotlin.gf2gamecommunity.base.composable.MyImage
import com.gin.kotlin.gf2gamecommunity.base.composable.TabInfo
import com.gin.kotlin.gf2gamecommunity.base.composable.TabRowPager
import com.gin.kotlin.gf2gamecommunity.base.util.htmlLink
import com.gin.kotlin.gf2gamecommunity.base.util.insertBySelection
import com.gin.kotlin.gf2gamecommunity.callback.AbstractNothingCallback
import com.gin.kotlin.gf2gamecommunity.composable.HtmlText
import com.gin.kotlin.gf2gamecommunity.composable.ImageUploadIconButton
import com.gin.kotlin.gf2gamecommunity.viewmodel.EmojiViewModel
import com.gin.kotlin.response.other.EmojiInfo
import kotlinx.coroutines.delay
import kotlinx.serialization.Serializable
import org.jsoup.nodes.Element


fun NavGraphBuilder.reply(onPopBackStack: () -> Unit) = composable<ReplyRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } },
) {
    ReplyComposable(route = it.toRoute(), onPopBackStack = onPopBackStack)
}


@Serializable
data class ReplyRoute(
    val topicId: Int,
    val commentId: Int = 0,
    val commentSubId: Int = 0,
) {
    fun toForm(content: String) = CommentReplyForm(topicId, content).also {
        it.commentId = this.commentId
        it.commentSubId = this.commentSubId
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ReplyComposable(route: ReplyRoute, onPopBackStack: () -> Unit) {
    // 正文
    var textFieldValue by remember { mutableStateOf(TextFieldValue("")) }
    var showEmojiDialog by remember { mutableStateOf(false) }

    Scaffold(
        topBar = {
            TopAppBar(navigationIcon = {
                IconButton(onClick = { onPopBackStack() }) {
                    Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "后退")
                }
            }, actions = {
                IconButton(onClick = {
                    App.INSTANCE.api.commentApi.reply(route.toForm(textFieldValue.text)).enqueue(object : AbstractNothingCallback() {
                        override fun onSuccess(message: String) {
                            App.INSTANCE.replyFlag = true
                            // 回复成功退出界面
                            App.toast(message)
                            onPopBackStack()
                        }
                    })

                }) {
                    Icon(painterResource(R.drawable.ic_send_24), contentDescription = "发送回复")
                }
            }, title = {
                Text("回复")
            })
        },

        ) { paddingValues ->
        val modifier = Modifier.padding(paddingValues)
        val focusRequester = remember { FocusRequester() }

        // 使用 LaunchedEffect 在界面加载时请求焦点
        LaunchedEffect(Unit) {
            // 延迟一小段时间以确保界面加载完成
            delay(500)
            focusRequester.requestFocus()
        }


        Column(modifier = modifier.fillMaxSize()) {
            TabRowPager(listOf(
                TabInfo("编辑") {
                    Column(modifier = Modifier.fillMaxSize()) {
                        TextField(value = textFieldValue, onValueChange = { textFieldValue = it }, label = { Text("回复正文") }, modifier = Modifier
                            .fillMaxWidth()
                            .focusRequester(focusRequester)
                            .weight(1f))

                        Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
                            ImageUploadIconButton { htmlImage, source ->
                                val htmlLink = source?.let { "${htmlLink(it, "来源")}<br/><br/>$htmlImage" }
                                textFieldValue = textFieldValue.insertBySelection(htmlLink ?: htmlImage)
                            }
                            IconButton(onClick = { showEmojiDialog = true }) {
                                Icon(imageVector = Icons.Filled.Face, contentDescription = "插入表情")
                            }
                        }
                    }
                },
                TabInfo("预览") {
                    Column(modifier = Modifier.fillMaxWidth()) {
                        HtmlText(item = Unit, html = "<p>${textFieldValue.text}</p>")
                    }
                },
            ))
        }
    }

    if (showEmojiDialog) EmojiDialog(title = "选择表情", onDismissRequest = { showEmojiDialog = false }, onClickEmoji = { _, html ->
        textFieldValue = textFieldValue.insertBySelection(html)
    })
}

@Composable
fun EmojiDialog(
    viewModel: EmojiViewModel = viewModel(),
    title: String? = null,
    onDismissRequest: () -> Unit,
    onClickEmoji: (emoji: EmojiInfo, html: String) -> Unit = { _, _ -> },
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit = {}
) {
    val list = viewModel.emojiList.fetch(false).observeAsState().value
    Dialog(onDismissRequest = onDismissRequest) {
        Card(
            shape = RoundedCornerShape(16.dp),
            modifier = modifier,
        ) {
            Column(
                modifier = modifier.padding(16.dp),
            ) {
                title?.let { Text(it, fontSize = 22.sp, fontWeight = FontWeight.Bold) }

                list?.also {
                    TabRowPager(list.map { classify ->
                        TabInfo(icon = {
                            MyImage(classify.imgAddr, modifier = Modifier.size(48.dp))
                        }) {
                            LazyVerticalGrid(columns = GridCells.Fixed(4), horizontalArrangement = Arrangement.spacedBy(4.dp),
                                verticalArrangement = Arrangement.spacedBy(4.dp)) {
                                items(items = classify.emojiList) {
                                    MyImage(it.urlPath, modifier = Modifier.clickable {
                                        val element = Element("img")
                                            .addClass("emoji")
                                            .attr("src", it.urlPath)
                                        onClickEmoji(it, element.toString())
                                    })
                                }
                            }
                        }
                    }, scrollable = true)
                } ?: Loading()

                content()
            }
        }
    }
}
